from collections import deque

#定义一个最大长度为3的双向队列
q =deque(maxlen=3)
q.append(1)
q.append(2)
q.append(3)
q.append(4)
# 使用append增加新元素，超出队列长度后，会将队首的元素移除，在队尾增加新元素
print(q)
# 使用appendleft 增加新元素，超出队列长度后，会将队队尾的元素移除，在队首增加新元素
q.appendleft(5)
print(q)




def prepare_test_file():
    with open('./PythonCookbookTest/liteng/10-16/test.txt','a') as file:
        for i in range(0,20):
            if i % 2 == 0:
                file.write('python\n')
            else:
                file.write('java\n')
        file.close()       

# prepare_test_file()

def search(lines, pattern, history=5):
    #声明一个双向队列，最大长度为5；如果队列已满，则移除最老的元素
    previous_lines = deque(maxlen=history)
    for line in lines:
        if pattern in line:
            # 将 line 和 previous_lines 作为生成器的每个item
            yield line, previous_lines
        previous_lines.append(line)

if __name__ == '__main__':
    with open(r'./PythonCookbookTest/liteng/10-16/test.txt','r') as f:
        for line, previous_lines in search(f,'python',5):
            print(line,previous_lines)
            for pline in previous_lines:
                    print(pline, end='')
                    print(line,end='')
                    print('-'*20)
        